package com.cyc.gulimall.cart.interceptor;

import com.cyc.common.vo.MemberResponseVo;
import com.cyc.gulimall.cart.vo.UserInfoVo;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;


public class CartInterceptor implements HandlerInterceptor {

    public static  ThreadLocal<UserInfoVo> threadLocal=new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoVo userInfoVo=new UserInfoVo();
        HttpSession session = request.getSession();
        MemberResponseVo loginUser = (MemberResponseVo) session.getAttribute("loginUser");
    if (loginUser!=null){
        userInfoVo.setUserId(loginUser.getId());


    }
        Cookie[] cookies = request.getCookies();
        if (cookies!=null && cookies.length>0){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (name.equals("user_cookie")){
                    userInfoVo.setUserKey(cookie.getValue());
                }
            }

        }

        if (StringUtils.isEmpty(userInfoVo.getUserKey())){
            String uuid = UUID.randomUUID().toString();
            userInfoVo.setUserKey(uuid);
        }




        threadLocal.set(userInfoVo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoVo userInfoVo = threadLocal.get();
        Cookie cookie = new Cookie("user_cookie", userInfoVo.getUserKey());
        cookie.setDomain("localhost");
        cookie.setMaxAge(60*60*24*30);

        response.addCookie(cookie);

    }
}
